#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    vector<int> advantageCount(vector<int>& A, vector<int>& B) {
        vector<int>indexA(A.size()), indexB(B.size());

        for (int i = 0; i < A.size(); ++i) {
            indexA[i] = i;
            indexB[i] = i;
        }
        sort(indexA.begin(), indexA.end(), [&](const int& left, const int& right) {
            return A[left] > A[right]; });
        sort(indexB.begin(), indexB.end(), [&](const int& left, const int& right) {
            return B[left] > B[right]; });
        vector<int>res(A.size());
        int left = 0, right = A.size();
        int leftA=0, leftB = 0;
        while (left < right) {
            if (A[indexA[leftA]] > B[indexB[leftB]]) {
                res[left++] = indexB[leftB++];
                ++leftA;
            }
            else {
                res[--right] = indexB[leftB++];
            }
        }
        vector<int>vec(A.size());
        for (int i = 0; i < res.size(); ++i) {
            vec[res[i]] = A[indexA[i]];
        }
        return vec;
    }
};